package com.sk.sk_frame_cloud.service.impl;

import com.sk.sk_frame_cloud.entity.ApplicationEntity;
import com.sk.sk_frame_cloud.res.CommonResponse;
import com.sk.sk_frame_cloud.service.IPropertiesServer;
import com.sk.sk_frame_cloud.util.FileCopyUtil;
import com.sk.sk_frame_cloud.util.XmlUtil;
import com.sk.sk_frame_cloud.util.YmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author jiaok
 * @Date 2023-12-08 15:22
 */
@Slf4j
@Service
public class IPropertiesServerImpl implements IPropertiesServer {

    @Resource
    private ResourceLoader resourceLoader;

    /**
     * 项目创建文件夹路径
     */
    @Value("${initPro.newProPath}")
    private String initProPath;

    /**
     * 架子项目路径
     */
    @Value("${initPro.frameProPath}")
    private String framePath;
    /**
     * 不同的项目拼接不同的后缀即可
     */
    private static  String  FILE_PATH = "classpath:sk-frame-pro-manage/templates/";
    @Override
    public CommonResponse initializePro(ApplicationEntity applicationEntity) {
        log.info("=========================== # IPropertiesServerImpl.initializePro #  ===========================");
        log.info("=========================== # 初始化...... #  ===========================");
//        String proConfigPath = FILE_PATH +"\\"+ applicationEntity.getPath();
//        File file = new File(proConfigPath);
//        file.mkdirs();
//        String ymlPath = proConfigPath +"\\"+ "application.yml";
//        String xmlPath = proConfigPath+ "\\"+"pom.xml";
//        // 项目源文件复制到新的路径
//        String proPath = initProPath + "\\"+applicationEntity.getPath();
//        String proYmlPath = proPath+"\\src\\main\\resources\\application.yml";
//        String proPomPath = proPath+"\\"+"pom.xml" ;
            FILE_PATH=initProPath+"\\"+"templates";
            String proConfigPath = FILE_PATH + "\\"+applicationEntity.getPath();
            File file = new File(proConfigPath);
            file.mkdirs();
            String ymlPath = proConfigPath +"\\"+ "application.yml";
            String xmlPath = proConfigPath+"\\"+ "pom.xml";
            // 项目源文件复制到新的路径

            String proPath = initProPath + "\\"+applicationEntity.getPath();
            String proYmlPath = proPath+"\\src\\main\\resources\\application.yml";
            String proPomPath = proPath+"\\"+"pom.xml" ;



            //复制新的yml配置文件
    //        FileCopyUtil.copyfile("src/main/resources/templates/frame.yml",ymlPath);
            //复制新的yml配置文件
            FileCopyUtil.copyfile(FILE_PATH+"\\"+"frame.yml",ymlPath);
            //复制新的pom文件
            FileCopyUtil.copyfile(FILE_PATH+"\\"+"sk_frame.xml",xmlPath);
            //拷贝出新的项目代码
            FileCopyUtil.directory(framePath,proPath);

            HashMap<String, Object> configMap = getConfigMap(applicationEntity);

            log.info("===========================  开始修改yml配置文件  ===========================");
            try {
                YmlUtil.bulkOperationConfig(ymlPath,configMap);
            } catch (Exception e) {
                log.error("===========================  修改yml配置文件出现错误  ===========================");
                throw new RuntimeException(e);
            }
            log.info("===========================  开始修改pom文件 ===========================");
            try {
                XmlUtil.updateFramePomXml(xmlPath,applicationEntity.getPath());
            } catch (IOException | DocumentException e) {
                log.error("===========================  修改pom文件出现错误  ===========================");
                throw new RuntimeException(e);
            }

            //配置文件修改完毕，开始替换文件
            FileCopyUtil.copyfile(ymlPath,proYmlPath);
            FileCopyUtil.copyfile(xmlPath,proPomPath);

        return CommonResponse.ok("文件修改成功");
    }

    /**
     * 生成对应的配置文件信息
     * @param applicationEntity 配置文件
     * @return
     */
    private static HashMap<String, Object> getConfigMap(ApplicationEntity applicationEntity) {
        String databaseName= applicationEntity.getDatabaseName();
        String databaseUrl="jdbc:mysql://"+ applicationEntity.getDatabaseIp()+":"+ applicationEntity.getDatabasePort()+"/"+ applicationEntity.getDatabaseName()
                +"?characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true";

        HashMap<String, Object> configMap = new HashMap<>();
        configMap.put("server.port", applicationEntity.getProPort());
        configMap.put("server.servlet.context-path","/"+ applicationEntity.getPath());
        configMap.put("spring.datasource.url",databaseUrl);
        configMap.put("spring.datasource.username", applicationEntity.getDatabaseUsername());
        configMap.put("spring.datasource.password", applicationEntity.getDatabasePassword());
        configMap.put("spring.redis.host", applicationEntity.getRedisIp());
        configMap.put("spring.redis.port", applicationEntity.getRedisPort());
        if (StringUtils.isNotBlank(applicationEntity.getRedisPassword())){
            configMap.put("spring.redis.password", applicationEntity.getRedisPassword());
        }
        configMap.put("api.live.url", applicationEntity.getLiveUrl());
        configMap.put("api.ai.url", applicationEntity.getAiUrl());
        configMap.put("nginx.path.images", applicationEntity.getNginxPicturePath());
        configMap.put("nginx.path.video", applicationEntity.getNginxVideoPath());
        return configMap;
    }

}
